<template>
  <div class="query-result">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <span>正在查询...</span>
    </div>
    
    <div v-else-if="error" class="error-message">
      <span class="error-icon">⚠️</span>
      {{ error }}
    </div>
    
    <div v-else-if="result" class="result-container">
      <div class="result-header">
        <span class="result-count">查询结果 ({{ result.total }}条记录)</span>
        <div class="header-controls">
          <button class="transpose-btn" @click="toggleTranspose" :class="{ active: isTransposed }">
            {{ isTransposed ? '正常视图' : '行转列' }}
          </button>
          <button class="fullscreen-btn" @click="openFullscreen" title="全屏查看">
            全屏查看
          </button>
          <button class="close-result" @click="$emit('close')">收起</button>
        </div>
      </div>
      
      <div class="table-wrapper" :class="{ 'transposed': isTransposed }">
        <!-- 正常视图 -->
        <table v-if="!isTransposed" class="result-table" ref="normalTable">
          <thead>
            <!-- 字段名行 -->
            <tr class="field-names">
              <th v-for="column in result.columns" :key="column.name" 
                  class="resizable-header" 
                  :style="getColumnStyle(column.name)"
                  :ref="'header-' + column.name">
                {{ column.name }}
                <div class="column-resizer" @mousedown="startResize($event, column.name)"></div>
              </th>
            </tr>
            <!-- 字段注释行 -->
            <tr class="field-comments">
              <th v-for="column in result.columns" :key="column.name + '_comment'" 
                  class="resizable-header"
                  :style="getColumnStyle(column.name)"
                  :ref="'comment-' + column.name">
                <div class="comment-content">
                  <span class="comment-text">{{ column.comment || '-' }}</span>
                  <button v-if="hasDictCode(column.comment)" 
                          class="dict-btn" 
                          @click="openDictDialog(column.comment)"
                          title="查看数据字典">
                    📖 查看字典
                  </button>
                  <button v-if="hasEnumName(column.comment)" 
                          class="enum-btn" 
                          @click="openEnumDialog(column.comment)"
                          title="查看Java枚举">
                    📊 查看枚举
                  </button>
                </div>
                <div class="column-resizer" @mousedown="startResize($event, column.name)"></div>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in result.rows" :key="index">
              <td v-for="column in result.columns" :key="column.name" :style="getColumnStyle(column.name)">
                {{ formatCellValue(row[column.name]) }}
              </td>
            </tr>
            <tr v-if="result.rows.length === 0">
              <td :colspan="result.columns.length" class="no-data">
                无数据
              </td>
            </tr>
          </tbody>
        </table>
        
        <!-- 行转列视图 -->
        <div v-else class="transposed-container" 
             @wheel="handleHorizontalScroll" 
             ref="transposedContainer">
          <!-- 固定的字段名和注释列 -->
          <div class="fixed-columns">
            <table class="fixed-table">
              <thead>
                <tr class="transposed-header">
                  <th class="field-label resizable-header">
                    字段名
                    <div class="column-resizer" @mousedown="startResize($event, 'field-name')"></div>
                  </th>
                  <th class="comment-label resizable-header">
                    字段注释
                    <div class="column-resizer" @mousedown="startResize($event, 'field-comment')"></div>
                  </th>
                </tr>
              </thead>
              <tbody ref="fixedTableBody">
                <tr v-for="(column, index) in result.columns" :key="'trans-fixed-' + column.name" 
                    class="transposed-row" :style="getTransposedRowStyle(index)">
                  <td class="field-name-cell" :style="getColumnStyle('field-name')">
                    {{ column.name }}
                  </td>
                  <td class="field-comment-cell" :style="getColumnStyle('field-comment')">
                    <div class="comment-content">
                      <span class="comment-text">{{ column.comment || '-' }}</span>
                      <button v-if="hasDictCode(column.comment)" 
                              class="dict-btn dict-btn-small" 
                              @click="openDictDialog(column.comment)"
                              title="查看数据字典">
                        📖
                      </button>
                      <button v-if="hasEnumName(column.comment)" 
                              class="enum-btn enum-btn-small" 
                              @click="openEnumDialog(column.comment)"
                              title="查看Java枚举">
                        📊
                      </button>
                    </div>
                  </td>
                </tr>
                <tr v-if="result.rows.length === 0">
                  <td colspan="2" class="no-data">
                    无数据
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 可滚动的数据列 -->
          <div class="scrollable-columns" ref="scrollableColumns">
            <table class="scrollable-table">
              <thead>
                <tr class="transposed-header">
                  <th v-for="(row, index) in result.rows" :key="'record-' + index" class="record-header resizable-header">
                    记录{{ index + 1 }}
                    <div class="column-resizer" @mousedown="startResize($event, 'record-' + index)"></div>
                  </th>
                </tr>
              </thead>
              <tbody ref="scrollableTableBody">
                <tr v-for="(column, index) in result.columns" :key="'trans-data-' + column.name" 
                    class="transposed-row" :style="getTransposedRowStyle(index)">
                  <td v-for="(row, dataIndex) in result.rows" :key="'data-' + dataIndex" 
                      class="data-cell" :style="getColumnStyle('record-' + dataIndex)">
                    {{ formatCellValue(row[column.name]) }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      
      <div v-if="result.hasMore" class="more-info">
        仅显示前100条记录
      </div>
    </div>
    
    <!-- 字典对话框 -->
    <DictDialog 
      :visible="showDictDialog"
      :dict-type="currentDictType"
      :dict-data="dictData"
      :loading="dictLoading"
      :error="dictError"
      @close="closeDictDialog"
    />
    
    <!-- 枚举对话框 -->
    <EnumDialog 
      :visible="showEnumDialog"
      :enum-name="currentEnumName"
      :enum-data="enumData"
      :loading="enumLoading"
      :error="enumError"
      @close="closeEnumDialog"
    />
    
    <!-- 全屏查看对话框 -->
    <div v-if="showFullscreen" class="fullscreen-overlay" @click="closeFullscreen" @keydown.esc="closeFullscreen">
      <div class="fullscreen-content" @click.stop>
        <div class="fullscreen-header">
          <span class="fullscreen-title">查询结果 ({{ result.total }}条记录) - 全屏查看</span>
          <div class="fullscreen-controls">
            <button class="transpose-btn" @click="toggleTranspose" :class="{ active: isTransposed }">
              {{ isTransposed ? '正常视图' : '行转列' }}
            </button>
            <button class="close-fullscreen" @click="closeFullscreen" title="关闭全屏">
              ✕
            </button>
          </div>
        </div>
        
        <div class="fullscreen-table-wrapper" :class="{ 'transposed': isTransposed }">
          <!-- 正常视图 -->
          <table v-if="!isTransposed" class="result-table fullscreen-table" ref="fullscreenNormalTable">
            <thead>
              <!-- 字段名行 -->
              <tr class="field-names">
                <th v-for="column in result.columns" :key="column.name" 
                    class="resizable-header" 
                    :style="getColumnStyle(column.name)"
                    :ref="'fullscreen-header-' + column.name">
                  {{ column.name }}
                  <div class="column-resizer" @mousedown="startResize($event, column.name)"></div>
                </th>
              </tr>
              <!-- 字段注释行 -->
              <tr class="field-comments">
                <th v-for="column in result.columns" :key="column.name + '_comment'" 
                    class="resizable-header"
                    :style="getColumnStyle(column.name)"
                    :ref="'fullscreen-comment-' + column.name">
                  <div class="comment-content">
                    <span class="comment-text">{{ column.comment || '-' }}</span>
                    <button v-if="hasDictCode(column.comment)" 
                            class="dict-btn" 
                            @click="openDictDialog(column.comment)"
                            title="查看数据字典">
                      📖 查看字典
                    </button>
                    <button v-if="hasEnumName(column.comment)" 
                            class="enum-btn" 
                            @click="openEnumDialog(column.comment)"
                            title="查看Java枚举">
                      📊 查看枚举
                    </button>
                  </div>
                  <div class="column-resizer" @mousedown="startResize($event, column.name)"></div>
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in result.rows" :key="index">
                <td v-for="column in result.columns" :key="column.name" :style="getColumnStyle(column.name)">
                  {{ formatCellValue(row[column.name]) }}
                </td>
              </tr>
              <tr v-if="result.rows.length === 0">
                <td :colspan="result.columns.length" class="no-data">
                  无数据
                </td>
              </tr>
            </tbody>
          </table>
          
          <!-- 行转列视图 -->
          <div v-else class="transposed-container fullscreen-transposed" 
               @wheel="handleHorizontalScroll" 
               ref="fullscreenTransposedContainer">
            <!-- 固定的字段名和注释列 -->
            <div class="fixed-columns">
              <table class="fixed-table">
                <thead>
                  <tr class="transposed-header">
                    <th class="field-label resizable-header">
                      字段名
                      <div class="column-resizer" @mousedown="startResize($event, 'field-name')"></div>
                    </th>
                    <th class="comment-label resizable-header">
                      字段注释
                      <div class="column-resizer" @mousedown="startResize($event, 'field-comment')"></div>
                    </th>
                  </tr>
                </thead>
                <tbody ref="fullscreenFixedTableBody">
                  <tr v-for="(column, index) in result.columns" :key="'trans-fixed-' + column.name" 
                      class="transposed-row" :style="getTransposedRowStyle(index)">
                    <td class="field-name-cell" :style="getColumnStyle('field-name')">
                      {{ column.name }}
                    </td>
                    <td class="field-comment-cell" :style="getColumnStyle('field-comment')">
                      <div class="comment-content">
                        <span class="comment-text">{{ column.comment || '-' }}</span>
                        <button v-if="hasDictCode(column.comment)" 
                                class="dict-btn dict-btn-small" 
                                @click="openDictDialog(column.comment)"
                                title="查看数据字典">
                          📖
                        </button>
                        <button v-if="hasEnumName(column.comment)" 
                                class="enum-btn enum-btn-small" 
                                @click="openEnumDialog(column.comment)"
                                title="查看Java枚举">
                          📊
                        </button>
                      </div>
                    </td>
                  </tr>
                  <tr v-if="result.rows.length === 0">
                    <td colspan="2" class="no-data">
                      无数据
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 可滚动的数据列 -->
            <div class="scrollable-columns" ref="fullscreenScrollableColumns">
              <table class="scrollable-table">
                <thead>
                  <tr class="transposed-header">
                    <th v-for="(row, index) in result.rows" :key="'record-' + index" class="record-header resizable-header">
                      记录{{ index + 1 }}
                      <div class="column-resizer" @mousedown="startResize($event, 'record-' + index)"></div>
                    </th>
                  </tr>
                </thead>
                <tbody ref="fullscreenScrollableTableBody">
                  <tr v-for="(column, index) in result.columns" :key="'trans-data-' + column.name" 
                      class="transposed-row" :style="getTransposedRowStyle(index)">
                    <td v-for="(row, dataIndex) in result.rows" :key="'data-' + dataIndex" 
                        class="data-cell" :style="getColumnStyle('record-' + dataIndex)">
                      {{ formatCellValue(row[column.name]) }}
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        
        <div v-if="result.hasMore" class="fullscreen-more-info">
          仅显示前100条记录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import DictDialog from './DictDialog.vue'
import EnumDialog from './EnumDialog.vue'
import { hasDictCode, getFirstDictCode, hasEnumName, getFirstEnumName } from '../utils/dictionary'
import { platformApi } from '../utils/api'
import configManager from '../utils/config'

export default {
  name: 'QueryResult',
  components: {
    DictDialog,
    EnumDialog
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    error: {
      type: String,
      default: null
    },
    result: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      isTransposed: false,
      columnWidths: {}, // 存储列宽度
      resizing: null, // 当前调整大小的列信息
      startX: 0,
      startWidth: 0,
      autoAdjusted: false, // 标记是否已经自动调整了列宽
      // 字典对话框状态
      showDictDialog: false,
      currentDictType: '',
      dictData: [],
      dictLoading: false,
      dictError: null,
      // 枚举对话框状态
      showEnumDialog: false,
      currentEnumName: '',
      enumData: [],
      enumLoading: false,
      enumError: null,
      // 全屏状态
      showFullscreen: false
    }
  },
  methods: {
    formatCellValue(value) {
      if (value === null) {
        return 'NULL'
      }
      if (value === undefined) {
        return ''
      }
      if (typeof value === 'object') {
        return JSON.stringify(value)
      }
      return String(value)
    },
    
    toggleTranspose() {
      this.isTransposed = !this.isTransposed
      // 重置列宽度
      this.columnWidths = {}
      
      // 如果切换到行转列模式，预计算数据列宽度
      if (this.isTransposed) {
        this.$nextTick(() => {
          this.preCalculateTransposedColumnWidths()
          // 如果在全屏模式下，重新设置滚动同步
          if (this.showFullscreen) {
            this.setupFullscreenScrollSync()
          }
        })
      }
    },
    
    getColumnStyle(columnKey) {
      const width = this.columnWidths[columnKey]
      return width ? { width: width + 'px', minWidth: width + 'px' } : {}
    },
    
    startResize(event, columnKey) {
      event.preventDefault()
      this.resizing = {
        column: columnKey,
        startX: event.clientX,
        startWidth: this.getColumnWidth(columnKey)
      }
      
      document.addEventListener('mousemove', this.handleResize)
      document.addEventListener('mouseup', this.stopResize)
      document.body.style.cursor = 'col-resize'
      document.body.style.userSelect = 'none'
    },
    
    handleResize(event) {
      if (!this.resizing) return
      
      const diff = event.clientX - this.resizing.startX
      const newWidth = Math.max(60, this.resizing.startWidth + diff) // 最小宽度60px
      
      this.$set(this.columnWidths, this.resizing.column, newWidth)
    },
    
    stopResize() {
      this.resizing = null
      document.removeEventListener('mousemove', this.handleResize)
      document.removeEventListener('mouseup', this.stopResize)
      document.body.style.cursor = ''
      document.body.style.userSelect = ''
    },
    
    getColumnWidth(columnKey) {
      // 如果已设置宽度，返回设置的宽度
      if (this.columnWidths[columnKey]) {
        return this.columnWidths[columnKey]
      }
      
      // 返回默认宽度
      if (columnKey === 'field-name') return 150
      if (columnKey === 'field-comment') return 200
      if (columnKey.startsWith('record-')) {
        // 对于数据列，计算最大内容宽度
        return this.calculateDataColumnWidth(columnKey)
      }
      return 120 // 普通列默认宽度
    },
    
    // 计算数据列的适合宽度（根据内容长度）
    calculateDataColumnWidth(columnKey) {
      if (!this.result || !this.result.rows || !columnKey.startsWith('record-')) {
        return 200 // 默认宽度
      }
      
      const recordIndex = parseInt(columnKey.replace('record-', ''))
      const record = this.result.rows[recordIndex]
      
      if (!record) return 200
      
      // 找到这个记录中最长的内容
      let maxLength = 0
      this.result.columns.forEach(column => {
        const value = this.formatCellValue(record[column.name])
        maxLength = Math.max(maxLength, String(value).length)
      })
      
      // 根据内容长度计算宽度（每个字符约8px，最小150px，最大500px）
      const calculatedWidth = Math.max(150, Math.min(500, maxLength * 8 + 30))
      
      return calculatedWidth
    },
    
    // 自动调整列宽以适应内容
    autoAdjustColumnWidths() {
      if (this.autoAdjusted || this.isTransposed || !this.result || !this.result.columns) {
        return
      }
      
      this.$nextTick(() => {
        const table = this.$refs.normalTable
        if (!table) return
        
        this.result.columns.forEach(column => {
          // 获取字段名和注释的宽度
          const headerRef = this.$refs['header-' + column.name]
          const commentRef = this.$refs['comment-' + column.name]
          
          if (headerRef && headerRef[0] && commentRef && commentRef[0]) {
            const headerWidth = this.getTextWidth(column.name) + 40 // 40px 为 padding 和 border
            const commentWidth = this.getTextWidth(column.comment || '-') + 40
            
            // 取两者中的最大值，但不小于最小宽度
            const maxWidth = Math.max(headerWidth, commentWidth, 100)
            
            // 设置列宽
            this.$set(this.columnWidths, column.name, maxWidth)
          }
        })
        
        this.autoAdjusted = true
      })
    },
    
    // 计算文本宽度的辅助方法
    getTextWidth(text, fontSize = '14px', fontFamily = 'Arial') {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      context.font = `${fontSize} ${fontFamily}`
      return context.measureText(text || '').width
    },
    
    // 获取行转列视图中行的样式（确保固定列和数据列高度一致）
    getTransposedRowStyle(index) {
      const baseHeight = 42 // 基础行高
      return {
        height: baseHeight + 'px',
        minHeight: baseHeight + 'px',
        maxHeight: baseHeight + 'px' // 限制最大高度，防止换行
      }
    },
    
    // 处理横向滚动事件
    handleHorizontalScroll(event) {
      // 只在行转列视图下生效
      if (!this.isTransposed) return
      
      event.preventDefault()
      
      // 根据当前模式选择正确的滚动容器
      const scrollableElement = this.showFullscreen 
        ? this.$refs.fullscreenScrollableColumns 
        : this.$refs.scrollableColumns
      
      if (!scrollableElement) return
      
      // 获取滚轮方向（横向滚动）
      const deltaX = event.deltaX || event.deltaY // 如果没有deltaX，使用deltaY
      
      // 调整滚动灵敏度
      const scrollAmount = deltaX * 2
      
      // 执行横向滚动
      scrollableElement.scrollLeft += scrollAmount
    },
    
    // 预计算行转列模式下数据列的宽度
    preCalculateTransposedColumnWidths() {
      if (!this.result || !this.result.rows) return
      
      this.result.rows.forEach((row, index) => {
        const columnKey = 'record-' + index
        const width = this.calculateDataColumnWidth(columnKey)
        this.$set(this.columnWidths, columnKey, width)
      })
    },
    
    // 字典相关方法
    hasDictCode,
    
    async openDictDialog(comment) {
      const dictCode = getFirstDictCode(comment)
      if (!dictCode) {
        return
      }
      
      // 检查平台配置
      if (!configManager.isPlatformConfigValid()) {
        alert('请先配置氧屋第三方平台信息')
        return
      }
      
      this.currentDictType = dictCode
      this.showDictDialog = true
      await this.loadDictData()
    },
    
    async loadDictData() {
      this.dictLoading = true
      this.dictError = null
      this.dictData = []
      
      try {
        const response = await platformApi.getDictDataByType(this.currentDictType)
        if (response.success && response.data && response.data.result) {
          this.dictData = response.data.result
        } else {
          this.dictError = '字典数据格式错误'
        }
      } catch (error) {
        this.dictError = error.message
      } finally {
        this.dictLoading = false
      }
    },
    
    closeDictDialog() {
      this.showDictDialog = false
      this.currentDictType = ''
      this.dictData = []
      this.dictError = null
    },
    
    // 枚举相关方法
    hasEnumName,
    
    async openEnumDialog(comment) {
      const enumName = getFirstEnumName(comment)
      if (!enumName) {
        return
      }
      
      // 检查平台配置
      if (!configManager.isPlatformConfigValid()) {
        alert('请先配置氧屋第三方平台信息')
        return
      }
      
      this.currentEnumName = enumName
      this.showEnumDialog = true
      await this.loadEnumData()
    },
    
    async loadEnumData() {
      this.enumLoading = true
      this.enumError = null
      this.enumData = []
      
      try {
        const response = await platformApi.getEnumDataByNames([this.currentEnumName])
        if (response.success && response.data && response.data.result) {
          this.enumData = response.data.result
        } else {
          this.enumError = '枚举数据格式错误'
        }
      } catch (error) {
        this.enumError = error.message
      } finally {
        this.enumLoading = false
      }
    },
    
    closeEnumDialog() {
      this.showEnumDialog = false
      this.currentEnumName = ''
      this.enumData = []
      this.enumError = null
    },
    
    // 全屏相关方法
    openFullscreen() {
      this.showFullscreen = true
      document.body.style.overflow = 'hidden'
      this.$nextTick(() => {
        // 为全屏模式添加键盘事件监听
        document.addEventListener('keydown', this.handleKeydown)
        // 为行转列模式添加滚动同步
        this.setupFullscreenScrollSync()
      })
    },
    
    closeFullscreen() {
      this.showFullscreen = false
      document.body.style.overflow = ''
      document.removeEventListener('keydown', this.handleKeydown)
      this.removeFullscreenScrollSync()
    },
    
    handleKeydown(event) {
      if (event.key === 'Escape' && this.showFullscreen) {
        this.closeFullscreen()
      }
    },
    
    // 设置全屏模式下的滚动同步
    setupFullscreenScrollSync() {
      if (!this.isTransposed) return
      
      this.$nextTick(() => {
        const fixedColumns = this.$refs.fullscreenTransposedContainer?.querySelector('.fixed-columns')
        const scrollableColumns = this.$refs.fullscreenScrollableColumns
        
        if (fixedColumns && scrollableColumns) {
          // 同步固定列和滚动列的纵向滚动
          const syncVerticalScroll = (source, target) => {
            source.addEventListener('scroll', () => {
              if (target.scrollTop !== source.scrollTop) {
                target.scrollTop = source.scrollTop
              }
            })
          }
          
          // 双向同步
          syncVerticalScroll(fixedColumns, scrollableColumns)
          syncVerticalScroll(scrollableColumns, fixedColumns)
          
          // 保存事件监听器引用以便清理
          this._fullscreenScrollSyncElements = { fixedColumns, scrollableColumns }
        }
      })
    },
    
    // 移除全屏模式下的滚动同步
    removeFullscreenScrollSync() {
      // 这里我们依赖DOM元素的生命周期来自动清理事件监听器
      // 当组件销毁或DOM元素移除时，事件监听器会自动清理
      this._fullscreenScrollSyncElements = null
    }
  },
  
  watch: {
    result: {
      handler() {
        this.autoAdjusted = false
        this.columnWidths = {}
        this.autoAdjustColumnWidths()
        // 在行转列模式下，预计算数据列宽度
        if (this.isTransposed) {
          this.preCalculateTransposedColumnWidths()
        }
      },
      immediate: true
    },
    isTransposed: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.preCalculateTransposedColumnWidths()
          })
        }
      }
    }
  },
  
  beforeDestroy() {
    // 清理事件监听器
    if (this.resizing) {
      document.removeEventListener('mousemove', this.handleResize)
      document.removeEventListener('mouseup', this.stopResize)
    }
    // 清理全屏相关事件监听器
    document.removeEventListener('keydown', this.handleKeydown)
    document.body.style.overflow = ''
  }
}
</script>

<style scoped>
.query-result {
  margin-top: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
  background: #f9fafb;
}

.loading {
  padding: 40px;
  text-align: center;
  color: #6b7280;
}

.spinner {
  display: inline-block;
  width: 24px;
  height: 24px;
  border: 3px solid #e5e7eb;
  border-top-color: #4f46e5;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  padding: 20px;
  color: #dc2626;
  background: #fee2e2;
  display: flex;
  align-items: center;
  gap: 10px;
}

.error-icon {
  font-size: 20px;
}

.result-container {
  background: white;
}

.result-header {
  padding: 15px 20px;
  background: #f3f4f6;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.transpose-btn {
  background: white;
  color: #4f46e5;
  border: 1px solid #4f46e5;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.transpose-btn:hover {
  background: #f0f9ff;
}

.transpose-btn.active {
  background: #4f46e5;
  color: white;
}

.result-count {
  color: #374151;
  font-weight: 600;
}

.close-result {
  background: white;
  color: #6b7280;
  border: 1px solid #d1d5db;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.close-result:hover {
  background: #f9fafb;
  color: #374151;
}

.fullscreen-btn {
  background: #4f46e5;
  color: white;
  border: 1px solid #4f46e5;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.fullscreen-btn:hover {
  background: #3730a3;
  border-color: #3730a3;
}

.table-wrapper {
  overflow-x: auto;
  max-height: 400px;
  overflow-y: auto;
}

.result-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.result-table th,
.result-table td {
  padding: 10px 15px;
  text-align: left;
  border: 1px solid #e5e7eb;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 可调整大小的表头 */
.resizable-header {
  position: relative;
}

.column-resizer {
  position: absolute;
  top: 0;
  right: 0;
  width: 4px;
  height: 100%;
  cursor: col-resize;
  background: transparent;
  z-index: 10;
}

.column-resizer:hover {
  background: rgba(79, 70, 229, 0.3);
}

/* 行转列容器样式 */
.transposed-container {
  display: flex;
  width: 100%;
  border: 1px solid #e5e7eb;
  position: relative;
  overflow: hidden; /* 防止容器溢出 */
}

.fixed-columns {
  flex-shrink: 0;
  border-right: 3px solid #16a34a; /* 绿色边框 */
  background: #f0fdf4; /* 浅绿色背景 */
  box-shadow: 2px 0 4px rgba(22, 163, 74, 0.1); /* 添加阴影效果 */
}

.scrollable-columns {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden; /* 隐藏垂直滚动条 */
  min-width: 0;
  scrollbar-width: thin; /* Firefox 细滚动条 */
  scrollbar-color: #16a34a #f0fdf4; /* Firefox 滚动条颜色 */
}

/* Webkit 浏览器滚动条样式 */
.scrollable-columns::-webkit-scrollbar {
  height: 8px;
}

.scrollable-columns::-webkit-scrollbar-track {
  background: #f0fdf4;
  border-radius: 4px;
}

.scrollable-columns::-webkit-scrollbar-thumb {
  background: #16a34a;
  border-radius: 4px;
}

.scrollable-columns::-webkit-scrollbar-thumb:hover {
  background: #15803d;
}

.fixed-table,
.scrollable-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.fixed-table {
  width: auto;
}

/* 行转列表格样式 */
.transposed-header th {
  background: #4f46e5;
  color: white;
  font-weight: 600;
  position: sticky;
  top: 0;
  z-index: 10;
  border: 1px solid #3730a3;
}

.field-label {
  min-width: 150px;
  background: #16a34a !important; /* 绿色表头 */
  color: white;
}

.comment-label {
  min-width: 200px;
  background: #15803d !important; /* 深绿色表头 */
  color: white;
}

.record-header {
  min-width: 120px;
  writing-mode: horizontal-tb;
}

.scrollable-table .transposed-row:nth-child(even) {
  background: #f9fafb;
}

.scrollable-table .transposed-row:hover {
  background: #f3f4f6;
}

.field-name-cell {
  font-weight: 600;
  background: #dcfce7; /* 浅绿色背景 */
  color: #166534;
  border: 1px solid #bbf7d0;
  padding: 10px 15px;
  position: relative;
}

.field-comment-cell {
  background: #ecfdf5; /* 更浅的绿色背景 */
  color: #15803d;
  font-size: 12px;
  border: 1px solid #bbf7d0;
  padding: 10px 15px;
  position: relative;
}

.data-cell {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  border: 1px solid #e5e7eb;
  padding: 10px 15px;
  position: relative;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出内容 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  min-width: 150px; /* 最小宽度 */
  max-width: 500px; /* 最大宽度 */
}

/* 确保固定列和滚动列高度一致 */
.fixed-table tr,
.scrollable-table tr {
  height: 42px;
}

.fixed-table th,
.scrollable-table th {
  height: 42px;
  line-height: 22px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.fixed-table td,
.scrollable-table td {
  height: 42px;
  vertical-align: middle;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 确保固定列和数据列的行对齐 */
.fixed-table tbody tr,
.scrollable-table tbody tr {
  border-bottom: 1px solid #e5e7eb;
}

.fixed-table tbody tr:nth-child(even) {
  background: #f0fdf4; /* 更深的绿色背景用于偶数行 */
}

.fixed-table tbody tr:hover {
  background: #dcfce7; /* 悬停时的绿色背景 */
}

.field-names th {
  background: #4f46e5;
  color: white;
  font-weight: 600;
  position: sticky;
  top: 0;
  z-index: 10;
}

.field-comments th {
  background: #6366f1;
  color: white;
  font-weight: 400;
  font-size: 12px;
  position: sticky;
  top: 38px;
  z-index: 10;
}

.result-table tbody tr:nth-child(even) {
  background: #f9fafb;
}

.result-table tbody tr:hover {
  background: #f3f4f6;
}

.no-data {
  text-align: center;
  color: #9ca3af;
  padding: 40px !important;
}

.more-info {
  padding: 10px 20px;
  background: #fef3c7;
  color: #92400e;
  font-size: 12px;
  text-align: center;
  border-top: 1px solid #fde68a;
}

/* 字典按钮样式 */
.comment-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  width: 100%;
}

.comment-text {
  flex: 1;
  word-break: break-word;
}

.dict-btn {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border: none;
  padding: 4px 8px;
  font-size: 11px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  flex-shrink: 0;
}

.dict-btn:hover {
  background: linear-gradient(135deg, #059669 0%, #047857 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(16, 185, 129, 0.3);
}

.dict-btn-small {
  padding: 2px 6px;
  font-size: 10px;
  min-width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 枚举按钮样式 */
.enum-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  padding: 4px 8px;
  font-size: 11px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  flex-shrink: 0;
  margin-left: 4px;
}

.enum-btn:hover {
  background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
}

.enum-btn-small {
  padding: 2px 6px;
  font-size: 10px;
  min-width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 2px;
}

/* 响应式表格 */
@media (max-width: 768px) {
  .table-wrapper {
    max-height: 300px;
  }
  
  .result-table {
    font-size: 12px;
  }
  
  .result-table th,
  .result-table td {
    padding: 8px 10px;
  }
  
  .dict-btn {
    font-size: 10px;
    padding: 2px 6px;
  }
  
  .enum-btn {
    font-size: 10px;
    padding: 2px 6px;
  }
  
  .comment-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
}

/* 全屏模式样式 */
.fullscreen-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(5px);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.fullscreen-content {
  background: white;
  border-radius: 12px;
  width: 100%;
  height: 100%;
  max-width: calc(100vw - 40px);
  max-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}

.fullscreen-header {
  padding: 20px 25px;
  background: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.fullscreen-title {
  color: #374151;
  font-weight: 600;
  font-size: 16px;
}

.fullscreen-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.close-fullscreen {
  background: #ef4444;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 40px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-fullscreen:hover {
  background: #dc2626;
  transform: scale(1.05);
}

.fullscreen-table-wrapper {
  flex: 1;
  overflow: auto;
  background: white;
  position: relative;
  height: 100%;
}

.fullscreen-table-wrapper.transposed {
  overflow: auto;
}

.fullscreen-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.fullscreen-transposed {
  height: 100%;
  display: flex;
}

.fullscreen-more-info {
  padding: 12px 25px;
  background: #fef3c7;
  color: #92400e;
  font-size: 12px;
  text-align: center;
  border-top: 1px solid #fde68a;
  flex-shrink: 0;
}

/* 确保全屏模式下表格样式与正常模式一致 */
.fullscreen-overlay .result-table th,
.fullscreen-overlay .result-table td {
  padding: 10px 15px;
  text-align: left;
  border: 1px solid #e5e7eb;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.fullscreen-overlay .field-names th {
  background: #4f46e5;
  color: white;
  font-weight: 600;
  position: sticky;
  top: 0;
  z-index: 10;
}

.fullscreen-overlay .field-comments th {
  background: #6366f1;
  color: white;
  font-weight: 400;
  font-size: 12px;
  position: sticky;
  top: 38px;
  z-index: 10;
}

.fullscreen-overlay .result-table tbody tr:nth-child(even) {
  background: #f9fafb;
}

.fullscreen-overlay .result-table tbody tr:hover {
  background: #f3f4f6;
}

/* 全屏模式下的行转列样式 */
.fullscreen-overlay .transposed-container {
  height: 100%;
}

.fullscreen-overlay .fixed-columns {
  flex-shrink: 0;
  border-right: 3px solid #16a34a;
  background: #f0fdf4;
  box-shadow: 2px 0 4px rgba(22, 163, 74, 0.1);
  overflow-y: auto;
  overflow-x: hidden;
}

.fullscreen-overlay .scrollable-columns {
  flex: 1;
  overflow-x: auto;
  overflow-y: auto;
  min-width: 0;
}

.fullscreen-overlay .transposed-header th {
  background: #4f46e5;
  color: white;
  font-weight: 600;
  position: sticky;
  top: 0;
  z-index: 10;
  border: 1px solid #3730a3;
}

.fullscreen-overlay .field-label {
  min-width: 150px;
  background: #16a34a !important;
  color: white;
}

.fullscreen-overlay .comment-label {
  min-width: 200px;
  background: #15803d !important;
  color: white;
}

.fullscreen-overlay .field-name-cell {
  font-weight: 600;
  background: #dcfce7;
  color: #166534;
  border: 1px solid #bbf7d0;
  padding: 10px 15px;
  position: relative;
}

.fullscreen-overlay .field-comment-cell {
  background: #ecfdf5;
  color: #15803d;
  font-size: 12px;
  border: 1px solid #bbf7d0;
  padding: 10px 15px;
  position: relative;
}

.fullscreen-overlay .data-cell {
  font-family: 'Courier New', monospace;
  font-size: 13px;
  border: 1px solid #e5e7eb;
  padding: 10px 15px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 150px;
  max-width: 500px;
}

/* 响应式全屏模式 */
@media (max-width: 768px) {
  .fullscreen-overlay {
    padding: 10px;
  }
  
  .fullscreen-header {
    padding: 15px 20px;
  }
  
  .fullscreen-title {
    font-size: 14px;
  }
  
  .fullscreen-controls {
    gap: 8px;
  }
  
  .close-fullscreen {
    padding: 6px 10px;
    font-size: 12px;
    min-width: 36px;
    height: 32px;
  }
}
</style>